<?php  

/** 
* Requests page (Controller) 
* Страничка заявок (контроллер) 
* @author IT studio IRBIS-team 
* @copyright © 2009 IRBIS-team 
*/
/////////////////////////////////////////////////////////

/**
* Generation of page of an error at access out of system
* Генерация страницы ошибки при доступе вне системы
*/
    if(!defined('IRB_KEY'))
    {
       header("HTTP/1.1 404 Not Found");      
       exit(file_get_contents('../../404.html'));
    } 
//////////////////////////////////////////////////////////

/**
* We connect a file of the MySQL functions
* Подключаем файл функций MySQL
*/  
   include './libs/mysql.php';
      
	$POST = htmlChars($POST);
	$request['id'] = !empty($GET['id'])?(int)$GET['id']:'';
	$cur_user_id = (int)$_SESSION['user_data']['id'];

/**
* Read
* Чтение
*/	
	if(!empty($request['id']))
	{
		$available_domains = getDomsOfUser($cur_user_id,10);
		$domains_of_this_request = getDomsOfRequest($request['id']);
		
		$res = mysqlQuery("SELECT 	r.*,
									u.name as o_name, 
									u.surname as o_sname,
									u.phone as o_phone,
									rt.caption as rt_caption
							FROM 
									`". IRB_DBPREFIX ."requests_types` rt,
									`". IRB_DBPREFIX ."user` u,
									`". IRB_DBPREFIX ."requests` r
							WHERE
									rt.id = r.type
								AND
									u.id = r.owner
								AND
									r.id ='".$request['id']."'");
		
		if(mysql_num_rows($res)>0)
			$r = mysql_fetch_assoc($res);
	
	$query = mysqlQuery("SELECT * FROM `". IRB_DBPREFIX ."requests_types`");
	if(mysql_num_rows($query)>0)
		{
		while($rt_row = mysql_fetch_assoc($query))
			$rt_array[] = $rt_row;
		}
	}

/**
* Write
* Запись
*/	
	if($ok)
		{
/**
* Обновляем привязку к доменам
*/		
			$arr_dotr = array();
			
			if(!empty($domains_of_this_request))
				{
				foreach($domains_of_this_request as $d_key => $d)
				$arr_dotr[] = $d['d_id'];
				}
				
			if(!empty($POST['array1']))
				{
				$arr_dotr_del = array_diff($arr_dotr,$POST['array1']);
				$arr_dotr_add = array_diff($POST['array1'],$arr_dotr);
				}
			
			if(!empty($arr_dotr_del))
			{
				foreach($arr_dotr_del as $del_key => $del_d_id)
					{
						mysqlQuery("DELETE FROM `". IRB_DBPREFIX ."requests_link_dom_user`
									WHERE 
										`user_id` = '".$cur_user_id."'
									AND
										`request_id` = '".$request['id']."'
									AND
										`dom_id` = '".$del_d_id."'");
					}
			}
			
			if(!empty($arr_dotr_add))
			{
				foreach($arr_dotr_add as $add_key => $add_d_id)
					{
						mysqlQuery("INSERT INTO `". IRB_DBPREFIX ."requests_link_dom_user`
									SET `user_id` = '".$cur_user_id."',
										`request_id` = '".$request['id']."',
										`dom_id` = '".$add_d_id."'");
					}
			}		

// Если домены обновились - обновляем их массив.			
			if(!empty($arr_dotr_del) || !empty($arr_dotr_add))
				$domains_of_this_request = getDomsOfRequest($request['id']);
		
		
// Если название есть и поменялось, то пишем в базу		
			if (!empty($POST['value2']) AND $r['title'] != $POST['value2'])
				{
				$r_title = "title='".$POST['value2']."'";
				$r['title'] = $POST['value2'];
				}
			else
				$r_title='';

// Если описание есть и поменялось, то пишем в базу					
			if (!empty($POST['value3']) AND $r['text'] != $POST['value3'])
				{
				$text = "text='".$POST['value3']."'";
				$r['text'] = $POST['value3'];
				}
			else
				$text='';
// Тип
			if(!empty($POST['value4']) AND $r['type'] != $POST['value4'])
				{
				$type = "type='".$POST['value4']."'";
				$r['type'] = $POST['value4'];
				}
			else
				$type='';
//Целевая дата				
			if(!empty($POST['value5']) AND $r['target_date'] != $POST['value5'])
				{
				$target_date = "target_date='".$POST['value5']."'";
				$r['target_date'] = $POST['value5'];
				}
			else
				$target_date='';
// Статус закрытой заявки
			if(isset($POST['value6']) && $POST['value6'] == 1)
				{
				$closed = "closed=0";
				$r['closed'] = 0;
				}
			else
				$closed='';
// Комментарий закрытой заявки			
			if(!empty($POST['value7']) AND $r['closed_comment'] != $POST['value7'])
				{
				$closed_comment = "closed_comment='".$POST['value7']."'";
				$r['closed_comment'] = $POST['value7'];
				}
			else
				$closed_comment='';
				
			if($r_title!='' || $text!='' || $type!='' || $target_date!='' || $closed!='' || $closed_comment!='')
				{
				mysqlQuery("UPDATE `". IRB_DBPREFIX ."requests`
						SET					 
						". $r_title . $text . $type . $target_date . $closed . $closed_comment ."
						WHERE `id` = ". $r['id'] );
				
				if(mysql_affected_rows() > 0)
					$info[] = "<p class='small ok'>Заявка успешно обновлена</p>";
				else
					$info[] = "<p class='small nok'>Заявка не обновлена.</p>";
				}
		}
     
